<?php
/**
 * Created by PhpStorm.
 * User: 69568
 * Date: 2018/2/7
 * Time: 11:23
 */

namespace App\Http\Controllers\Api;


use App\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Resources\MoneyLogRescource;
use App\Models\MoneyLog;
use App\Models\Stock;
use Illuminate\Http\Request;

class StockController extends Controller
{
    use ApiResponse;

    public function buy(Request $request)
    {
        $num = $request->input('num', 0);
        if ($num <= 0) {
            return $this->message("购买数量必须大于0", [], 400);
        } else {
            $user_id = $request->user('api')->id;
            $insert['user_id'] = $user_id;
            $insert['num'] = $num;
            $insert['price'] = 10000;
            $insert['status'] = false;
            $insert['stock_num'] = config('stock_value') * $num;
            $insert['order_no'] = "S" . date('YmdHis') . rand(1000, 9999);
            Stock::create($insert);
            return $this->message('申请成功');
        }
    }

    public function logs(Request $request)
    {
        $logs = MoneyLog::whereUserId($request->user('api')->id)->where('type','stock')->orderBy('created_at', 'desc')->paginate();
        return $this->message('获取成功',MoneyLogRescource::collection($logs));
    }

    public function stock(Request $request)
    {
        /** @var \App\Models\User $user */
        $user = $request->user('api');
        $stocks = Stock::whereUserId($user->id)->orderBy('created_at', 'desc')->paginate();
        return $this->message('获取成功', $stocks->items());
    }

    public function ratio(Request $request)
    {
        $logs = MoneyLog::whereUserId($request->user('api')->id)->where('type','radio')->orderBy('created_at', 'desc')->paginate();
        return $this->message('获取成功',MoneyLogRescource::collection($logs));
    }
}